#include<iostream>
#include<unistd.h>
#include<fcntl.h>
#include<cstring>
#include<cstdio>
#include<sys/types.h>
#include<sys/wait.h>

void childWrite(int fd){
    const char* str = "hello world!\n";
    int cnt = 5;
    while(cnt--){
        ssize_t s = write(fd,str,strlen(str));
        if(s < 0){
            perror("write failed");
            exit(2);
        }
        sleep(1);
    }
}

void fatherRead(int fd){
    char buffer[1024];
    while (true){
        ssize_t n = read(fd, buffer, sizeof(buffer) - 1);
        if (n < 0){
            perror("read failed");
            exit(3);
        }
        else if(n == 0){
            break;
        }
        printf("读取的实际字节数为%zd\n",n);
        buffer[n] = 0;
        printf("%s",buffer);
    }
    
}

int main(){
    int fds[2];
    int ret = pipe(fds);
    if(ret < 0){
        std::cerr<<"pipe error:"<<strerror(errno)<<std::endl;
        exit(1);
    }
    pid_t id = fork();
    if(id == 0){
        close(fds[0]);
        childWrite(fds[1]);
        close(fds[1]);
        exit(0);
    }

    close(fds[1]);
    fatherRead(fds[0]);
    close(fds[0]);
    int status = 0;
    int rid = waitpid(id,&status,0);
    if(rid < 0){
        perror("wait failed");
        exit(4);
    }
    printf("Child exit status: %d\n", WEXITSTATUS(status));
    return 0;
}